package middleware

import (
	"blockchain_data/middleware/filerotator"
	"blockchain_data/utils"
	"fmt"
	"github.com/robfig/cron/v3"
	"github.com/sirupsen/logrus"
	"sync"
	"time"
)

var log *logrus.Logger

type SaveData struct {
	Goods string `json:"goods"`
	ContractCode string `json:"contract_code"`
	Bourse string `json:"bourse"`
	Path string `json:"path"`
	MaxAge time.Duration `json:"maxAge"`
	Spec string `json:"spec"`
	Server string `json:"server"`
	Timing string `json:"timing"`
	Ws interface{} `json:"ws"`
	C *cron.Cron `json:"c"`
}

func (this *SaveData)Init (goods string,contractCode string ,bourse string,server string, ws interface{})   {
	this.Goods = goods
	this.ContractCode = contractCode
	this.Bourse = bourse
	this.Server = server
	this.Ws = ws
	path := fmt.Sprintf("%s/data/%s/%s/%s/%s/",utils.GetCurrentPath(),bourse,goods,server,contractCode)
	this.Path = path
	log = DataLogger()
}


// todo 订阅tick数据 （需要继承重写）
func (this *SaveData)SubTrade()  {
}

// todo 取消价格订阅（需要继承重写）
func (this *SaveData)UnSubTrade(goods string,contractCode string) int  {
	return 0
}
// 定时删除数据
func (this *SaveData) DeleteTradeDetail(maxAge time.Duration,spec string)  {

	file := "*.csv"

	cleaner, err := filerotator.NewTimeBasedCleaner(this.Path+file, maxAge)

	if err != nil {
		log.Error("保存数据出错. %v\n", err)
	}

	c := cron.New()
	//0    12   *   *   *
	//#分  时   日   月  周
	c.AddFunc(spec, func() {
		deleted, err := cleaner.Clean()
		if err != nil {
			fmt.Printf("%v\n", err)
			return
		}
		for _, d := range deleted {
			fmt.Printf("删除文件%s\n", d)
		}
	})
	c.Start()
	this.C = c
}

// 停止定时删除任务
func (this *SaveData) CloseDeleteTradeDetail()  {
	this.C.Stop()
}

// 保存数据
func (this *SaveData) SaveTradeDetail(s string)  {
	wgTradeDetail := new(sync.WaitGroup)
	file := "%Y%m%d%H.csv"
	writer, err := filerotator.NewTimeBasedRotator(this.Path + file, 1 * time.Hour,8)
	if err != nil {
		log.Error("保存数据出错. %v\n", err)
	}
	defer writer.Close()
	wgTradeDetail.Add(1)
	go func() {
		_, err := writer.Write([]byte(s))
		if err != nil {
			fmt.Printf("保存数据出错, %v\n", err)
		}
		wgTradeDetail.Add(-1)
	}()
	wgTradeDetail.Wait()
}

